<!-- 公共组件-分页
    参数：
    total：数据总条数  (必传)
    pageSize.sync：每页显示条目个数  (必传)
    currentPage.sync：当前页数   (必传)
    @currentChange：分页改变事件，直接绑定网络请求即可，无需参数，sync已经改变父组件分页数据  （后端返回数据没有分页时不传）
    @sizeChange：分页数量改变事件，直接绑定网络请求即可，无需参数，sync已经改变父组件分页数据  （后端返回数据没有分页时不传）
    tableData.sync：表单数据 （后端返回数据没有分页时传，组件进行前端分页）
 -->
<template>
    <div class="e-pagination" v-if="total !== 0">
        <el-pagination
            layout="prev, pager, next, jumper, sizes, total"
            :total="total"
            :page-size.sync="_pageSize"
            :current-page.sync="_currentPage"
            :page-sizes="[20, 50, 100, 1000, 2000]"
            ref="elPagination"
            @size-change="sizeChange"
            @current-change="currentChange"
            :tableData="tableData"
            :key="refresh"
        >
        </el-pagination>
    </div>
    <div class="e-pagination" v-else style="height: 33px;">
    </div>
</template>

<script>
import goImg from '@/assets/go.png'
import { debounce } from '@/utils/common'
export default {
    props: {
        // 总条目数
        total: {
            type: Number,
            default: 0
        },
        // 每页显示条目个数
        pageSize: {
            type: Number,
            default: 10
        },
        // 当前页数
        currentPage: {
            type: Number,
            default: 1
        },
        // 表单数据（获取数据没有分页时传）
        tableData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 表单是否是model，model只能在父组件用emit更新
        tableDataIsModel: {
            type: Boolean,
            default: false
        }
    },
    data: function () {
        return {
            cloneTableData: [],
            fn: null,
            // pageState: false,
            refresh: 0 // element ui bug total不更新，刷新key来重置组件
        }
    },
    computed: {
        _pageSize: {
            get () {
                return this.pageSize
            },
            set (size) {
                if (this.tableData.length === 0) {
                    this.$emit('update:pageSize', size)
                } else {
                    this.$emit('update:pageSize', size)
                    this.pageSize = size
                }
            }
        },
        _currentPage: {
            get () {
                return this.currentPage
            },
            set (page) {
                if (this.tableData.length === 0) {
                    this.$emit('update:currentPage', page)
                } else {
                    this.$emit('update:currentPage', page)
                    this.currentPage = page
                }
            }
        }
    },
    watch: {
        // elementUi有bug，total不更新，只能用v-if等待total有值再显示，需求需要变更dom样式，所以监听total改变生成了分页dom再改变dom
        total (val) {
            this.refresh += 1
            if (val !== 0) {
                setTimeout(() => {
                    // 添加go图标
                    const go = '<img class="go" />'
                    const elQuerySelector = attr => this.$refs.elPagination.$el.querySelector(attr)
                    $(elQuerySelector('.el-pagination__editor')).prepend(go)
                    $(elQuerySelector('.go')).attr('src', goImg)
                    $(elQuerySelector('.go')).css({
                        position: 'absolute',
                        right: '5px',
                        top: '5px'
                    })
                    // 添加首末
                    const start = '<li class="start">首页</li>'
                    const end = '<li class="end">尾页</li>'
                    $(elQuerySelector('.el-pager')).prepend(start)
                    $(elQuerySelector('.el-pager')).append(end)
                    const txt = elQuerySelector('.el-pagination__total').innerText
                    $(elQuerySelector('.el-pagination__total')).text(
                        txt.substr(0, 2) +
                            '⌈' +
                            txt.substring(2, txt.length - 2) +
                            '⌋' +
                            txt.substr(txt.length - 2)
                    )
                    $(elQuerySelector('.el-pager')).prepend(
                        elQuerySelector('.el-pagination__total')
                    )
                    $(elQuerySelector('.start')).bind('click', event => {
                        event.stopPropagation()
                        this._currentPage = 1
                        this.currentChange()
                    })
                    $(elQuerySelector('.end')).bind('click', event => {
                        event.stopPropagation()
                        const totalPage = Math.ceil(this.total / this._pageSize)
                        this._currentPage = totalPage
                        this.currentChange()
                    })
                }, 0)
            }
        },
        tableData: {
            handler () {
                this.cloneTableData = JSON.parse(JSON.stringify(this.tableData))
            },
            deep: true
        }
    },
    mounted () {},
    created () {
        console.log('this.tableData', this.tableData)
        if (this.tableData.length !== 0) {
            this.cloneTableData = JSON.parse(JSON.stringify(this.tableData))
            this.frontPaging()
        }
        this.fn = debounce(this.handle)
        console.log('total', this.total)
    },
    methods: {
        // 前端分页方法
        frontPaging () {
            const start = (this._currentPage - 1) * this._pageSize
            // 父组件table不是model
            if (this.tableDataIsModel === false) {
                this.$emit(
                    'update:tableData',
                    this.cloneTableData.slice(start, start + this._pageSize)
                )
            } else {
                // 父组件table是model
                this.$emit(
                    'tableDataIsModelFun',
                    this.cloneTableData.slice(start, start + this._pageSize)
                )
            }
        },
        sizeChange () {
            this.fn('sizeChange')
        },
        currentChange () {
            this.fn('currentChange')
        },
        handle (evType) {
            if (evType === 'sizeChange') {
                if (this.$listeners.sizeChange === undefined) {
                    this.frontPaging()
                } else {
                    this.$emit('sizeChange')
                }
            } else {
                if (this.$listeners.currentChange === undefined) {
                    this.frontPaging()
                } else {
                    this.$emit('currentChange')
                }
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.e-pagination ::v-deep.el-pagination__jump {
    font-size: 0;
    overflow: hidden;
}

.e-pagination ::v-deep.el-pagination__editor {
    width: 100px !important;
}
</style>
